<?php
//php防注入和XSS攻击通用过滤
$_GET && SafeFilter($_GET);
$_POST && SafeFilter($_POST);
$_COOKIE && SafeFilter($_COOKIE);
function SafeFilter(&$arr){
    $ra = array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '/script/', '/javascript/', '/vbscript/', '/expression/', '/applet/'
    , '/meta/', '/xml/', '/blink/', '/link/', '/style/', '/embed/', '/object/', '/frame/', '/layer/', '/title/', '/bgsound/'
    , '/base/', '/onload/', '/onunload/', '/onchange/', '/onsubmit/', '/onreset/', '/onselect/', '/onblur/', '/onfocus/',
        '/onabort/', '/onkeydown/', '/onkeypress/', '/onkeyup/', '/onclick/', '/ondblclick/', '/onmousedown/', '/onmousemove/'
    , '/onmouseout/', '/onmouseover/', '/onmouseup/', '/onunload/','/\+/');

    if (is_array($arr)) {
        foreach ($arr as $key => $value) {
            if (!is_array($value)) {
                if (!get_magic_quotes_gpc())  //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
                {
                    if($value != addslashes($value)) getTheAttack(); //给单引号（'）、双引号（"）、反斜线（\）与 NUL（NULL 字符）
                    //加上反斜线转义
                }
                foreach ($ra as $s_k => $s_v){
                    $matches = array();
                    preg_match($s_v,$value,$matches);
                    if(!empty($matches)) getTheAttack();
                }               
                if($value != htmlentities(strip_tags($value))) getTheAttack();

            } else {
                SafeFilter($arr[$key]);
            }
        }
    }
}


function getTheAttack(){
    exit(json_encode(array('code'=>0,'msg'=>'输入的内容有非法字符','data'=>array())));
}
